package com.course.api.service.Impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.course.api.entity.User;
import com.course.api.mapper.UserMapper;
import com.course.api.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    UserMapper userMapper;


    @Override
    public IPage<User> Page(IPage<User> userIPage, Wrapper<User> queryWrapper) {
        return userMapper.selectPage(userIPage, queryWrapper);
    }

    @Override
    public List<User> selectTeacherList(String userType) {
        return userMapper.selectList(new QueryWrapper<User>().eq("user_type", userType));
    }

    @Override
    public User selectCourse(Long courseId, Long userId) {
        User user = userMapper.selectById(userId);
        String courseIds = user.getCourseIds();
        if (courseIds == null || courseIds.equals("")) {
            courseIds = courseId.toString();
        } else {
            courseIds = courseIds + ',' + courseId.toString();
        }
        user.setCourseIds(courseIds);
        userMapper.updateById(user);
        return user;
    }

    @Override
    public User deselectCourse(Long courseId, Long userId) {
        User user = userMapper.selectById(userId);
        String courseIds = user.getCourseIds();
        int index = courseIds.indexOf(courseId.toString());
        if (courseIds.length() == 1) {
            courseIds = "";
        } else {
            if (index == 0) {
                courseIds = courseIds.replace(courseId + ",", "");
            } else if (index > 0) {
                courseIds = courseIds.replace("," + courseId, "");
            }
        }
        user.setCourseIds(courseIds);
        userMapper.updateById(user);
        return user;
    }
}
